
package com.ai.networking.netty.service;

import com.ai.networking.netty.decoder.L1ToSysMessageDecoder;
import com.ai.networking.netty.handler.HearBeatHandler;
import com.ai.networking.netty.handler.ServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;

/**
 * 监听 Socket 服务
 *
 * @author chen
 */
@Slf4j
public class NettyServer implements Runnable {

    int[] ports;

    /**
     * 通过构造方法将端口信息注入
     * 单个服务端可以监听多个端口
     * @param ports
     */
    public NettyServer(int[] ports) {
        this.ports = ports;
    }

    /**
     * Socket监听
     */

    public void SocketListener(int... ports) {
        log.info("================NettyServer开始启动========================");
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            //绑定线程池
            bootstrap.group(bossGroup, workerGroup)
                    // 指定使用的channel
                    .channel(NioServerSocketChannel.class)
                    .childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(256, 256, 65535))
                    // 绑定客户端连接时候触发操作
                    .childHandler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //获取客户端的ip信息
                            InetAddress ip = ch.remoteAddress().getAddress();
                            //客户端的端口
                            int port = ch.remoteAddress().getPort();

                            String address = ip.getHostAddress();

                            ch.pipeline().addLast(new L1ToSysMessageDecoder());
                            ch.pipeline().addLast(new IdleStateHandler(60, //没有收到客户端发送的数据，就会抛出读超时异常事件
                                    0, //0s服务端没有给客户端发送数据，就会抛出写超时异常事件
                                    0)); //30s内读写事件都没有发生，就会抛出全超时异常事件
                            ch.pipeline().addLast(new HearBeatHandler());//处理超时事件

                            ch.pipeline().addLast(new ServerHandler(address,port));
                        }
                    });

            log.info("================NettyServer 启动中.....========================");
            ChannelFuture[] channelFutures;
            ChannelFuture futureTcp;
            if (ports.length > 0) {
                System.out.println("====================有"+ports.length+"个端口=========================");
                channelFutures = new ChannelFuture[ports.length];
                int i = 0;
                for (Integer port : ports) {
                    System.out.println("====================启动端口："+port+"=========================");
                    // 绑定端口，同步等待成功 绑定的服务器
                    futureTcp = bootstrap.bind(port);
                    channelFutures[i++] = futureTcp;
                    futureTcp.addListener(future -> {
                        if (future.isSuccess()) {
                            System.out.println("netty server 启动成功!" + port);
                        } else {
                            System.out.println("netty server 启动失败!" + port);
                        }
                    });
                }
                log.info("================NettyServer 启动完毕！！========================");
                for (ChannelFuture future : channelFutures) {
                    /**
                     * 等待服务器监听端口关闭
                     * 手动阻塞所有的信道，当信道关闭之后，自动释放线程
                     */
                    future.channel().closeFuture().sync();
                }
                log.info("================NettyServer 关闭服务器通道！！========================");
            }
        } catch (Exception e) {
            log.error("================ NettyServer  启动出现异常， 异常内容为：" + e.getMessage() + "========================");
        } finally {
            log.error("================ NettyServer 服务关闭========================");
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
    @Override
    public void run() {
        log.info("================多线程启动Netty Server========================");
        this.SocketListener(ports);
    }
}
